import { request } from "./httpHelper";
const md5 = require("js-md5");

const database = "test";
// const tag_stable = database + "." + "tconfig";
const tag_table = database + "." + "ttag";
const neuron_table = database + "." + "tneuron";
const auth = "Basic cm9vdDp0YW9zZGF0YQ==";
const header = {
  Authorization: auth,
  "Content-Type": "text/plain",
};
const config = {
  method: "post",
  url: "/tdengine/rest/sql",
  headers: header,
  data: "sql",
};

// 分页获取点位
const getPagedTags = async (query, skipCount, resultCount) => {
  let sql = "select * from " + tag_table;

  if (query.neuron) {
    sql += ' where nhost = "' + query.neuron + '"';
    if (query.node) {
      sql += ' and node = "' + query.node + '"';
      if (query.group) {
        sql += ' and groupname = "' + query.group + '"';
      }
    }
  }

  sql += " order by ts desc";

  if (skipCount === undefined || resultCount === undefined) {
    sql += " limit 0,5";
  } else {
    sql += " limit " + skipCount + "," + resultCount;
  }

  config.data = sql;
  let resp = await request(config);

  let result0 = transform(resp);

  let sql0 = "select count(*) as data from " + tag_table;

  if (query.neuron) {
    sql0 += ' where nhost = "' + query.neuron + '"';
    if (query.node) {
      sql0 += ' and node = "' + query.node + '"';
      if (query.group) {
        sql0 += ' and groupname = "' + query.group + '"';
      }
    }
  }
  config.data = sql0;
  let resp0 = await request(config);
  let num =
    transform(resp0).data.length == 0
      ? 0
      : Number(transform(resp0).data[0].data);
  let result = {
    data: result0.data,
    total: num,
  };

  return result;
};

// 编辑点位
const editTag = async (obj) => {
  if (obj) {
    let id = obj.ts;
    // let had = await hasTag(id, tag_stable);

    // if (had.total != 0) {
    //   // 有这个点位，删掉
    //   await deleteTag(id);
    // }

    // insert into ttag values (now, 'tag1', '1#2c', '三轧五线', 'http://192.168.128.129:7000', 'modbus1', 'group1')

    if (String(id).search("-") != -1) {
      id = '"' + id + '"';
    }

    config.data =
      "insert into " +
      tag_table +
      " values (" +
      id +
      ", " +
      '"' +
      obj.tagname +
      '", ' +
      '"' +
      obj.receivename +
      '", ' +
      '"' +
      obj.neuron +
      '", ' +
      '"' +
      obj.nhost +
      '", ' +
      '"' +
      obj.node +
      '", ' +
      '"' +
      obj.groupname +
      '")';

    // console.log(config.data);

    let resp = await request(config);
    console.log(resp);
  }
};

// 删除点位
const deleteTag = async (id) => {
  config.data = "delete from " + tag_table + ' where ts = "' + id + '"';
  let rs = await request(config);
  console.log(rs);
};

// 判断是否有这个点位，并返回这个点位
const hasTag = async (id, table) => {
  config.data = "select count(*) from " + table + ' where ts = "' + id + '"';
  let resp = await request(config);
  let result = transform(resp);
  return result;
};

// 获取neuron
const getNeurons = async (query, skipCount, resultCount) => {
  let sql = "select * from " + neuron_table;
  if (query && query != "") {
    sql += ' where neuron like "%' + query + '%"';
  }
  if (skipCount != 0 && resultCount != 0) {
    sql += " limit " + skipCount + "," + resultCount;
  }

  config.data = sql;
  let resp = await request(config);
  return transform(resp);
};

// 编辑neuron
const editNeuron = async (obj) => {
  if (obj) {
    config.data =
      "insert into " +
      neuron_table +
      " values (" +
      obj.ts +
      ', "' +
      obj.neuron +
      '", "' +
      obj.nhost +
      '")';

    let resp = await request(config);
    console.log(resp);
  }
};

// 判断是否有这个neuron的tag
const existNeuron = async (neuron, nhost) => {
  if (neuron && nhost) {
    let sql =
      "select neuron, nhost from " +
      tag_table +
      ' where neuron = "' +
      neuron +
      '" and nhost = "' +
      nhost +
      '"';

    config.data = sql;
    let resp = await request(config);
    let result = transform(resp);

    if (result.total > 0) {
      return true;
    } else {
      return false;
    }
  }
  return false;
};

// 查询first EP
const getFirstEp = async () => {
  let sql = "select last(first_ep) from log.cluster_info";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    return result.data[0].first_ep;
  }
};

// 查询version
const getVersion = async () => {
  let sql = "select last(version) from log.cluster_info";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log(result.data[0].version);
    return result.data[0].version;
  }
};

// 查询master uptime
const getMasterUptime = async () => {
  let sql = "select last(master_uptime) from log.cluster_info";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log(result.data[0].master_uptime);
    let week = result.data[0].master_uptime / 60 / 60 / 24 / 7;
    return week.toFixed(2);
  }
};

// 查询databases
const getDatabases = async () => {
  let sql = "show databases";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  return result.data.length;
};

// 查询tables
const getTables = async () => {
  let sql = "show databases";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    let num = 0;
    result.data.forEach((v) => {
      num += Number(v.ntables);
    });
    return num;
  }
};

// 查询connections
const getConnections = async () => {
  let sql = "select last(connections_total) from log.cluster_info";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log(result.data[0].connections_total);
    return result.data[0].connections_total;
  }
};

// 查询近半个小时cpu使用率
const getCpus = async () => {
  let sql =
    "select * from (select ts, cpu_engine, cpu_system from log.dnodes_info order by ts desc limit 60) order by ts";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log(result.data);
    return result.data;
  }
};

// 查询cpu当前使用率
const getCpu1 = async () => {
  let sql = "select last(cpu_system) from log.dnodes_info";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log((Number(result.data[0].cpu_engine)*100).toFixed(2));
    return Number(result.data[0].cpu_system).toFixed(2);
  }
};

// 查询内存占用率
const getMemory = async () => {
  let sql = "select last(mem_system), last(mem_total) from log.dnodes_info";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log(
    //   (Number(result.data[0].mem_engine) / 1000).toFixed(2),
    //   (Number(result.data[0].mem_total) / 1000).toFixed(2)
    // );
    return {
      mem_engine: (Number(result.data[0].mem_system) / 1000).toFixed(2),
      mem_total: (Number(result.data[0].mem_total) / 1000).toFixed(0),
    };
  }
};

// 查询磁盘占用率
const getDisk = async () => {
  let sql = "select last(disk_used), last(disk_total) from log.dnodes_info";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log(
    //   (Number(result.data[0].mem_engine) / 1000).toFixed(2),
    //   (Number(result.data[0].mem_total) / 1000).toFixed(2)
    // );
    return {
      disk_used: Number(result.data[0].disk_used).toFixed(2),
      disk_total: Number(result.data[0].disk_total).toFixed(0),
    };
  }
};

// 查询磁盘,网络读写速度
const getIO = async () => {
  let sql =
    "select last(io_read_disk), last(io_write_disk), last(net_in), last(net_out) from log.dnodes_info";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log(result.data);
    return result.data[0];
  }
};

// 查询点位列表
const queryPointList = async (key) => {
  let sql = "select distinct tagname from emq.test_neuron";
  if (key) {
    sql += " where tagname like '%" + key + "%'";
  }
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  return result.data;
};

// 查询点位历史数据
const queryHistory = async (point, dts, dte) => {
  let cha = (new Date(dte) - new Date(dts)) / 1000;
  let interval = "1s";
  if (cha > 3600) {
    cha = cha / 3600;
    interval = cha + "s";
  }
  let sql =
    "select last(ts, value) from emq." +
    point +
    " where ts between '" +
    dts +
    "'" +
    " and '" +
    dte +
    "' interval(" +
    interval +
    ")";
  (" order by ts asc");
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  return result;
};

// 查询处理http request
const getRequest = async () => {
  let sql =
    "select * from (select sum(count) as total from log.taosadapter_restful_http_total interval(30s) order by ts desc limit 60) order by ts";
  config.data = sql;
  let resp = await request(config);
  let result = transform(resp);
  if (result.data.length != 0) {
    // console.log(result.data);
    return result.data;
  }
};

// ----------------------- utils -----------------------
// 转换TDengine返回的消息
const transform = (resp) => {
  let result = {
    total: 0,
    data: [],
  };

  if (resp) {
    if (resp.status === "succ") {
      result.total = resp.rows;
      let respData = resp.data;
      let head = resp.head;
      for (let i = 0; i < respData.length; i++) {
        let body = "{";
        for (let j = 0; j < respData[i].length; j++) {
          let element = respData[i][j];
          if (j != 0) {
            body += ',"' + head[j] + '": "' + element + '"';
          } else {
            body += '"' + head[j] + '": "' + element + '"';
          }
        }
        body += "}";
        result.data.push(JSON.parse(body));
      }
    }
  }

  return result;
};

// 获取时间戳
const getTimestamp = () => {
  return new Date().getTime().toString();
};

export { getPagedTags, editTag, getNeurons, deleteTag, editNeuron };
export {
  getFirstEp,
  getVersion,
  getMasterUptime,
  getDatabases,
  getTables,
  getConnections,
  getCpus,
  getCpu1,
  getMemory,
  getDisk,
  getIO,
  getRequest,
};
export { queryPointList, queryHistory };
